package com.woniu.adopt.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.adopt.entity.Pet;
import com.woniu.adopt.entity.RescueStation;
import com.woniu.adopt.mapper.PetMapper;
import com.woniu.adopt.mapper.RescueStationMapper;
import com.woniu.adopt.vo.PetVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RescueStationService {

    @Autowired
    RescueStationMapper rescueStationMapper;

    @Autowired
    PetMapper petMapper;

    //模糊查询 （救助站名称，地址）+ 分页
    public PageInfo<RescueStation> queryRSByPage(Integer now, Integer size, String name, String address) {
        PageHelper.startPage(now, size);

        List<RescueStation> rescueStations = rescueStationMapper.selectRSByName(name, address);

        return new PageInfo<>(rescueStations);
    }

    //模糊查询  已注销（救助站名称，地址）+ 分页
    public PageInfo<RescueStation> queryOldRSByPage(Integer now, Integer size, String name, String address) {
        PageHelper.startPage(now, size);

        List<RescueStation> rescueStations = rescueStationMapper.selectOldRSByName(name, address);
        return new PageInfo<>(rescueStations);
    }

    //查询所有的救助站信息
    public List<RescueStation> queryAllRole() {
        return rescueStationMapper.selectAll();
    }


    //添加救助站
    public void insertRS(RescueStation rescueStation) {
        rescueStationMapper.insert(rescueStation);
    }

    //删除救助站
    //首先判断当前救助站的id，是否有宠物在，有就提示不能删除当前救助站，没有宠物占用，则可删
    public int removeRS(int id) {
        //首先判断当前救助站的id，是否被还未被收养的宠物使用
//        List<Pet> pets = rescueStationMapper.selectPetByRSid(id);
        //没有被使用，直接删除====(此处逻辑删)
//        if (pets.size() == 0) {
            //返回受影响的行数，也只能是1
            int i = rescueStationMapper.updateDelByKey(id);
            return i;
//        } else {
            //代表被宠物使用，不可删，返回0
//            return 0;
//        }
    }

    //真删除救助站
    @Transactional
    public int removeRS2(int id) {
        //查询该救助站所拥有宠物
        int result=petMapper.selectByRSId(id);
        if (result == 0) {
            //返回受影响的行数，也只能是1
            int i = rescueStationMapper.deleteByPrimaryKey(id);

            return i;
        }
        return 0;
    }

    //修改救助站信息
    public int updateRS(RescueStation rescueStation) {
        return rescueStationMapper.updateByPrimaryKey(rescueStation);
    }


    public RescueStation selectRSByKey(int id) {
        RescueStation rescueStation = rescueStationMapper.queryRSByKey(id);
        return rescueStation;
    }
}
